package com.lishem.top100._07linkedlist;

import com.lishem.common.ListNode;

/**
 * https://leetcode.cn/problems/merge-two-sorted-lists/description/
 * <p>
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * <p>
 * 示例 1：
 * <p>
 * 输入：l1 = [1,2,4], l2 = [1,3,4]
 * <p>
 * 输出：[1,1,2,3,4,4]
 * <p>
 * 示例 2：
 * <p>
 * 输入：l1 = [], l2 = []
 * <p>
 * 输出：[]
 * <p>
 * 示例 3：
 * <p>
 * 输入：l1 = [], l2 = [0]
 * <p>
 * 输出：[0]
 */
public class _05LetCode21_合并两个有序链表 {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode tmpHead = new ListNode();
        ListNode tmpTail = tmpHead;
        while (list1 != null || list2 != null) {
            if (list1 == null) {
                tmpTail.next = list2;
                break;
            } else if (list2 == null) {
                tmpTail.next = list1;
                break;
            } else {
                if (list1.val < list2.val) {
                    tmpTail.next = list1;
                    list1 = list1.next;
                } else {
                    tmpTail.next = list2;
                    list2 = list2.next;
                }
                tmpTail = tmpTail.next;
            }
        }
        return tmpHead.next;
    }

    public static void main(String[] args) {
        _05LetCode21_合并两个有序链表 sol = new _05LetCode21_合并两个有序链表();
        ListNode list1 = new ListNode(1);
        list1.next = new ListNode(2);
        list1.next.next = new ListNode(4);

        ListNode list2 = new ListNode(1);
        list2.next = new ListNode(3);
        list2.next.next = new ListNode(4);
        ListNode.printListNode(sol.mergeTwoLists(list1, list2));
    }
}
